﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

using System.Text;
using HZ.DrugTrade.Model;
using HZ.Data;
namespace HZ.DrugTrade.DAL
{
    /// <summary>
    /// 消息系统DAL层
    /// </summary>
    public class DAL_Message
    {
        /// <summary>
        /// 添加通告
        /// </summary>
        /// <param name="notices"></param>
        /// <returns></returns>
        public static int AddNotice_Batch(IList<Notice> notices)
        {
            //foreach (var item in notices)
            //{
            //    HZ.Data.DAL_Helper.OperateTableSQL<Notice>(item, TableOperator.Insert);
            //}

            //庄金冬修改：添加通告应当只有一条信息，可以有多个接收群体【接收群体通过关系表实现】
            /*
              string strSplit = ",";
              IDataParameter[] paras = new IDataParameter[] { 
                  new SqlParameter("@in_NoticeSerialID", Guid.NewGuid().ToString()),
                  new SqlParameter("@in_RecieveRoleIDs", HZ.Data.DAL_Helper.GetModelFieldArrayString(notices,"Reciever"  ,strSplit)),
                  new SqlParameter("@in_Sender", notices[0].Sender),
                  new SqlParameter("@in_Title", notices[0].Title),
                  new SqlParameter("@in_NoticeContent", notices[0].NoticeContent),
                  new SqlParameter("@in_PostUser", notices[0].PostUser),
                  new SqlParameter("@out_Success",SqlDbType.Int)
              };
              paras[paras.Length - 1].Direction = ParameterDirection.Output;

              HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(CommandType.StoredProcedure, "usp_Notice_Add_Batch", paras);

              return (int)paras[paras.Length - 1].Value;
             * */
            int Flag = 0;
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("begin");
                sb.AppendLine(string.Format(@" INSERT INTO TB_Notice (NoticeSerialID,Sender, SendTime,Title,NoticeContent, NoticeType, PostUser )
                  VALUES( '{0}', '{1}', sysdate,  '{2}', '{3}', 0,  '{4}' );", notices[0].NoticeSerialID, notices[0].Sender, notices[0].Title, notices[0].NoticeContent, notices[0].PostUser));
                foreach (var item in notices)
                {
                    sb.AppendLine(string.Format("INSERT INTO  TB_NoticeRecieveRole( NoticeSerialID, RecieveRole) VALUES ('{0}', '{1}' );",item.NoticeSerialID,item.Reciever));
                }
                sb.AppendLine(" end; ");
                h.ExecuteNonQuery(sb.ToString());
                h.CommitTrans();
                Flag = 1;
            }
            catch
            {
                h.RollTrans();
                Flag = 0;
            }
            return Flag;

        }

        /// <summary>
        /// 批量添加消息并存到发件箱
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static int AddMessage_Save_Batch(IList<Message> message)
        {
            int flag = 0;
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                foreach (var item in message)
                {
                    //item.flag = 0;
                    //h.ExecuteNonQuery(HZ.Data.DAL_Helper.GetInsertSql(item));
                    //item.MessageID = Guid.NewGuid().ToString();
                    //item.flag = 1;
                    //h.ExecuteNonQuery(HZ.Data.DAL_Helper.GetInsertSql(item));
                    item.flag = 0;
                    HZ.Data.DAL_Helper.OperateTableSQL(item, TableOperator.Insert, h);
                    item.MessageID = Guid.NewGuid().ToString();
                    item.flag = 1;
                    HZ.Data.DAL_Helper.OperateTableSQL(item, TableOperator.Insert, h);
                }
                h.CommitTrans();
                flag = 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DAL_Message", ee.Message, ee);
                flag = 0;
            }

            return flag;
        }

        /// <summary>
        /// 批量添加消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static int AddMessage_Batch(IList<Message> message)
        {
            int flag = 0;
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                foreach (var item in message)
                {
                    item.flag = 0;
                    //h.ExecuteNonQuery(HZ.Data.DAL_Helper.GetInsertSql(item));
                    HZ.Data.DAL_Helper.OperateTableSQL(item, TableOperator.Insert, h);
                }
                h.CommitTrans();
                flag = 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DAL_Message", ee.Message, ee);
                flag = 0;
            }

            return flag;
        }


        /// <summary>
        /// 更新消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static int UpdateMessage(Message message)
        {
            return HZ.Data.DAL_Helper.OperateTableSQL<Message>(message, TableOperator.Update);
        }

        /// <summary>
        /// 条件查询消息[已收信息]
        /// </summary>
        /// <param name="where"></param>
        /// <param name="p"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public static IList<HZ.DrugTrade.Model.View.Message> GetMessage(HZ.DrugTrade.Model.Query.Message where, string p, int currentpage, int pagesize, out int totalrecord)
        {
            where.Append = string.Format("Reciever = '{0}' AND flag=0 ", p);
            return HZ.DrugTrade.DAL2.DAL_Helper.GetPagedView<HZ.DrugTrade.Model.View.Message, HZ.DrugTrade.Model.Query.Message>(where, currentpage, pagesize, out totalrecord);
        }


        /// <summary>
        /// 添加反馈
        /// </summary>
        /// <param name="feedback"></param>
        /// <returns></returns>
        public static int AddFeedBack(FeedBack feedback)
        {
            return HZ.Data.DAL_Helper.OperateTableSQL(feedback, TableOperator.Insert);
        }


        /// <summary>
        /// 批量增加反馈
        /// </summary>
        /// <param name="feedbackList"></param>
        /// <returns></returns>
        public static int AddFeedBack_Batch(IList<FeedBack> feedbackList)
        {
            int flag = 0;
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                foreach (var item in feedbackList)
                {
                    //h.ExecuteNonQuery(HZ.Data.DAL_Helper.GetInsertSql(item));
                    HZ.Data.DAL_Helper.OperateTableSQL(item, TableOperator.Insert, h);
                }
                h.CommitTrans();
                flag = 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DAL_Message", ee.Message, ee);
                flag = 0;
            }

            return flag;

        }


        /// <summary>
        /// 回复反馈
        /// </summary>
        /// <param name="feedback"></param>
        /// <returns></returns>
        public static int ReplyFeedBack(FeedBack feedback)
        {
            return HZ.Data.DAL_Helper.OperateTableSQL(feedback, TableOperator.Update);
        }


        /// <summary>
        /// 更新反馈状态
        /// </summary>
        /// <param name="feedback"></param>
        /// <returns></returns>
        public static int UpdateFeedBack_Status(FeedBack feedback)
        {
            return HZ.Data.DAL_Helper.OperateTableSQL(feedback, TableOperator.Update);
        }

        public static IList<HZ.DrugTrade.Model.View.FeedBack> GetFeedBack_Manager(HZ.DrugTrade.Model.Query.FeedBack where, string orgID, int currentpage, int pagesize, out int totalrecord)
        {
            where.Append = string.Format(" Reciever = '{0}'", orgID);

            return HZ.DrugTrade.DAL2.DAL_Helper.GetPagedView<HZ.DrugTrade.Model.View.FeedBack, HZ.DrugTrade.Model.Query.FeedBack>(where, currentpage, pagesize, out totalrecord);

        }

        public static IList<HZ.DrugTrade.Model.View.FeedBack> GetFeedBack_Sender(HZ.DrugTrade.Model.Query.FeedBack where, string orgID, int currentpage, int pagesize, out int totalrecord)
        {
            where.Append = string.Format(" Sender = '{0}'", orgID);

            return HZ.DrugTrade.DAL2.DAL_Helper.GetPagedView<HZ.DrugTrade.Model.View.FeedBack, HZ.DrugTrade.Model.Query.FeedBack>(where, currentpage, pagesize, out totalrecord);
        }

        /// <summary>
        /// 批量删除消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static int DeleteMessage_Batch(IList<Message> message)
        {
            int flag = 0;
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                foreach (var item in message)
                {
                    h.ExecuteNonQuery(string.Format(@"DELETE FROM  TB_Message WHERE MessageID= '{0}'", item.MessageID));
                }
                h.CommitTrans();
                flag = 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DAL_Message", ee.Message, ee);
                flag = 0;
            }

            return flag;
        }

        public static IList<HZ.DrugTrade.Model.View.Message> GetMessageSent(HZ.DrugTrade.Model.Query.Message where, string p, int currentpage, int pagesize, out int totalrecord)
        {
            where.Append = string.Format("Sender = '{0}' AND flag=1 ", p);
            return HZ.DrugTrade.DAL2.DAL_Helper.GetPagedView<HZ.DrugTrade.Model.View.Message, HZ.DrugTrade.Model.Query.Message>(where, currentpage, pagesize, out totalrecord);
        }

        /// <summary>
        /// 批量删除公告
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static int DeleteNotice_Batch(IList<Notice> message)
        {
            int flag = 0;
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                foreach (var item in message)
                {
                    h.ExecuteNonQuery(string.Format(@"DELETE FROM  TB_NoticeRecieveRole
                WHERE NoticeSerialID= '{0}'", item.NoticeSerialID));
                    h.ExecuteNonQuery(string.Format(@"DELETE FROM  TB_Notice
                WHERE NoticeSerialID= '{0}'", item.NoticeSerialID));
                }
                h.CommitTrans();
                flag = 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DAL_Message", ee.Message, ee);
                flag = 0;
            }

            return flag;
        }


        /// <summary>
        /// 批量删除公告
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static int DeleteFeedBack_Batch(IList<FeedBack> feedbackList)
        {
            int flag = 0;
            var h = HZ.Data.DbHelperFactory.Create();
            try
            {
                h.BeginTrans();
                foreach (var item in feedbackList)
                {
                    h.ExecuteNonQuery(string.Format(@"DELETE FROM  TB_FeedBack  WHERE FeedBackID= '{0}'", item.FeedBackID));
                }
                h.CommitTrans();
                flag = 1;
            }
            catch (Exception ee)
            {
                h.RollTrans();
                HZ.Common.log4netManager.LogDebug("DAL_Message", ee.Message, ee);
                flag = 0;
            }

            return flag;
        }


        /// <summary>
        /// 获取待审核的通知公告
        /// </summary>
        /// <param name="where"></param>
        /// <param name="currentpage"></param>
        /// <param name="pagesize"></param>
        /// <param name="totalrecord"></param>
        /// <returns></returns>
        public static IList<Model.View.Notice> GetAuditNotice(Model.Query.Notice where, int currentpage, int pagesize, out int totalrecord)
        {
            string strwhere = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition(where, true);

            string sql = string.Format(@"SELECT distinct SenderName,
                                            RoleNames,
                                            NoticeSerialID,
                                            Sender,
                                            SendTime,
                                            Title,
                                            NoticeContent,
                                            AuditStatus,
                                            NoticeType,
                                            AuditUser,
                                            PostUser,'' AS Reciever
                                            FROM View_Notice where 1=1 {0}", strwhere);

            HZ.Data.PageDescribe des = new HZ.Data.PageDescribe(sql, pagesize);
            des.CurrentPage = currentpage;
            totalrecord = des.TotalCount;

            return HZ.Data.DAL_Helper.CommonFillList<Model.View.Notice>(des.GetSpecailPage());
        }

    }
}
